package com.mb.microservice.framework.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.mb.microservice.framework.core.entity.Result;

/**
 * @program: framework
 * @description:
 * @author: wys1890
 * @create: 2020-11-19 10:11
 **/
public class JsonUtils {
    
    public static final JsonMapper JSON_MAPPER = new JsonMapper();
    
    static {
        // 如果存在未知属性，则忽略不报错
        JSON_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许key没有双引号
        JSON_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        // 允许key有单引号
        JSON_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 美化输出
        JSON_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
        // 允许序列化空的POJO类
        // （否则会抛出异常）
        JSON_MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        // 把java.util.Date, Calendar输出为数字（时间戳）
//        MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 在遇到未知属性的时候不抛出异常
        JSON_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 强制JSON 空字符串("")转换为null对象值:
        JSON_MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        //在序列化时忽略值为默认值的属性
        JSON_MAPPER.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
        JSON_MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    }
    
    
    public static <T> T json2Bean(String jsonString, Class<T> clazz) throws JsonProcessingException {
        return JSON_MAPPER.readValue(jsonString, clazz);
    }
    
    public static String bean2Json(Object obj) throws JsonProcessingException {
        return JSON_MAPPER.writeValueAsString(obj);
    }
    
    //test
    public static void main(String[] args) throws Exception {
        Result result = new Result();
        result.setStatus(null);
        result.setMsg("null");
        result.setData(null);
        String json = JsonUtils.bean2Json(result);
        System.out.println(json);
        //注意转Java对象的时候会调用默认构造方法
        System.out.println(JSON.parseObject(json, Result.class));
        System.out.println(JsonUtils.json2Bean(json, Result.class));
    }
}
